package com.kuangstudy.alipay.web;

import com.alibaba.fastjson.JSONObject;
import com.kuangstudy.alipay.service.pay.AlipayService;
import com.kuangstudy.alipay.service.pay.PayCommonService;
import com.kuangstudy.alipay.vo.PayVo;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


/**
 * @description: 阿里支付接口类
 * @author: xuke
 * @time: 2020/9/8 23:34
 */
@Controller
@Log4j2
public class AliPayController {

    @Autowired
    private AlipayService alipayService;
    @Autowired
    private PayCommonService payCommonService;

    /*
     * @Author xuke
     * @Description 阿里支付接口
     * @Date 23:35 2020/9/8
     * @Param [request, session]
     * @return byte[]
     **/
    @ResponseBody
    @RequestMapping("/alipay/pay")
    public byte[] alipaycourse(String courseid) throws IOException {
        //2：组装支付的参数
        PayVo payVo = new PayVo();
        payVo.setUserId("1");
        payVo.setCourseid(courseid);
        //3:生成支付的微信二维码
        return alipayService.alipay(payVo);
    }

    /**
     * 异步通知
     */
    @ResponseBody
    @RequestMapping("/alipay/notifyUrl")
    public String notify_url(HttpServletRequest request) throws Exception {
        boolean result = alipayCallback(request);
        if (result) {
            return "success"; // 请不要修改或删除
        } else {
            // 验证失败
            return "fail";
        }
    }

    /**
     * 支付宝回调
     *
     * @return
     * @throws Exception
     */
    private boolean alipayCallback(HttpServletRequest request) throws Exception {
        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, new String(valueStr.getBytes("ISO-8859-1"), "UTF-8"));
        }

        // 计算得出通知验证结果
        log.info("1：---->获取支付宝回传的参数---------------------------------->" + params);
        // 返回公共参数
        String extparamString = request.getParameter("extra_common_param");
        log.info("2---->：支付宝交易返回的参数：{}", extparamString);
        String tradeno = params.get("trade_no");;
        //交易完成
        String body = params.get("body");
        if (StringUtils.isEmpty(tradeno)) {
            tradeno = params.get("trade_no");
        }
        log.info("3---->:【支付宝】交易的参数信息是：{}，流水号是：{}", body, tradeno);
        try {
            JSONObject bodyJson = JSONObject.parseObject(body);
            String userId = bodyJson.getString("userId");
            String ptype = bodyJson.getString("ptype");
            String orderNumber = bodyJson.getString("orderNumber");
            log.info("4---->:【支付宝】交易的参数信息是：ptype:{}，orderNumber是：{}",  ptype,orderNumber);
            // 课程支付
            if (ptype != null && ptype.equalsIgnoreCase("productcourse")) {
                payCommonService.payproductcourse(bodyJson, userId, orderNumber, tradeno, "1");
            }
        } catch (Exception ex) {
            log.info("支付宝支付出现了异常.....");
            ex.printStackTrace();
            return false;
        }
        return true;
    }
}
